package com.cjh.mybatis07.bind;


import com.cjh.mybatis07.session.SqlSession;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @description: 映射器代理类
 * @author: cjh
 * @date: 2023/5/23 - 20:05
 */
@Data
@AllArgsConstructor
public class MapperProxy<T> implements InvocationHandler, Serializable {
    private static final long serialVersionUID = 1L;

    private SqlSession sqlSession;
    private final Class<T> mapperInterface;
    /**
     * 这加个缓存干什么
     */
    private final Map<Method, MapperMethod> methodCache;


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//        如果是调用Object类的方法 就不增强
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
        } else {
            final MapperMethod mapperMethod = cachedMapperMethod(method);
            return mapperMethod.execute(sqlSession, args);
        }

    }

    private MapperMethod cachedMapperMethod(Method method) {
        MapperMethod mapperMethod = methodCache.get(method);
        if (mapperMethod == null) {
//            找不到才去new
            mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());

            methodCache.put(method, mapperMethod);
        }
        return mapperMethod;
    }
}
